﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Testing
{
    public static class NativeMemory
    {
        public struct MemoryStatus
        {
            internal uint dwLength; 
            public int MemoryLoad; 
            public int TotalPhysical; 
            public int AvailablePhysical; 
            public int TotalPageFile; 
            public int AvailablePageFile; 
            public int TotalVirtual; 
            public int AvailableVirtual;

            public string AvailableAsString
            {
                get
                {
                    return FormatFileSize(AvailablePhysical);
                }
            }
        }

        public static string FormatFileSize(int size)
        {
            if (size <= 1000) return string.Format("{0} Byte", size);
            if (size < 100000) return string.Format("{0:F} KB", (float)(((size + 500F) / 1000F)));
            return string.Format("{0:F} MB", (float)(((size + 500F) / 1000000F)));
        }

        [DllImport("coredll", SetLastError = false)]
        private static extern void GlobalMemoryStatus(out MemoryStatus status);

        public static MemoryStatus GetMemoryStatus()
        {
            MemoryStatus status;
            GlobalMemoryStatus(out status);
            return status;
        }
    }
}
